package com.yuanqi.hnucshop.service.impl;

import com.yuanqi.hnucshop.entity.User;
import com.yuanqi.hnucshop.mapper.UserMapper;
import com.yuanqi.hnucshop.service.UserService;
import com.yuanqi.hnucshop.utils.HttpClientHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public Integer register(User user) {

        /**
         * 判断是否为空，为空则不添加
         */
        if (user == null || user.getOpenid() == null ) return 0;

        userMapper.addUser(user);
        return 1;
    }

    @Override
    public User selectUser(String openid) {

        if (openid.equals("")) return null;

        return userMapper.selectUser(openid);

    }


    @Override
    public Boolean verifyUser(String openid, String code) {


        /**
         * wxAPI,根据code验证openid，一致则验证成功
         */
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" +
                "wx2ad016ddbb21599d&secret=30601f882ca5f3e01e7710d8371632f9&js_code=" +
                code+"&grant_type=authorization_code";

        String res;
        try {res = HttpClientHelper.sendGet(url);
        } catch (IOException e) {
            return false;
        }

        if (res.contains(openid) || res.contains("code been used")) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean updateUser(User user) {

        /**
         * 判断是否为空，为空则不更新
         */
        if (user == null || user.getOpenid() == null ) return false;

        userMapper.updateUser(user);
        return true;
    }


    @Override
    public List<User> selectAllUser() {

        List<User> users = userMapper.selectAllUser();

        return users;
    }
}
